#
# pymoz, Python extension for the Mozilla Toolkit
# Copyright (C) 2012 Malek Hadj-Ali
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#


import sysconfig
import os
import sys
import argparse


get_var = sysconfig.get_config_var

python_name = "".join(("python", get_var("VERSION")))
if os.name == "nt":
    python_libname = python_name
else:
    python_libname = "".join((python_name, sys.abiflags))


exclude_flags = set(["-g", "-DNDEBUG", "-Wall", "-Wstrict-prototypes"])

# we use a list instead of a set difference to keep the flags ordered
# (wish OrderedSet would be in std lib)
def strip_flags(flags):
    result = []
    for flag in flags:
        if flag not in exclude_flags and flag not in result:
            result.append(flag)
    return result


def pymoz_includes():
    """print the Python includes required to build pymoz and exit."""
    includes = (sysconfig.get_path("include"), sysconfig.get_path("platinclude"))
    return " ".join(set(("".join(("-I", path)) for path in includes)))


def pymoz_libname():
    """print the Python library name pymoz will load and exit."""
    return python_libname


def pymoz_cflags():
    """print the Python CFLAGS required to build pymoz and exit."""
    if os.name == "nt":
        cflags = []
    else:
        cflags = get_var("CFLAGS").split()
    return " ".join(strip_flags(cflags))


def pymoz_libs():
    """print the Python libs required to build pymoz and exit."""
    if os.name == "nt":
        lib_path = os.path.join(os.path.normpath(sys.exec_prefix), "libs")
        libs = [os.path.join(lib_path, "".join((python_name, ".lib")))]
    else:
        libs = " ".join((get_var("LIBS"), get_var("SYSLIBS"))).split()
        libs.append("".join(("-l", python_libname)))
        if not get_var("Py_ENABLE_SHARED"):
            libs.insert(0, "".join(("-L", get_var("LIBPL"))))
        libs.extend(get_var("LINKFORSHARED").split())
    return " ".join(strip_flags(libs))



pymoz_options = {
                 "--includes": pymoz_includes,
                 "--libname": pymoz_libname,
                 "--cflags": pymoz_cflags,
                 "--libs": pymoz_libs,
                }


class PrintAndExitAction(argparse.Action):

    def __init__(self, option_strings, dest=argparse.SUPPRESS, help=None,
                 value=None):
        help = help or (value.__doc__ if callable(value) else None)
        super().__init__(option_strings, dest, nargs=0, help=help)
        self.value = value

    def __call__(self, parser, namespace, values, option_string=None):
        print(self.value() if callable(self.value) else self.value)
        parser.exit()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    group = parser.add_mutually_exclusive_group(required=True)
    for key, value in pymoz_options.items():
        group.add_argument(key, action=PrintAndExitAction, value=value)
    parser.parse_args()
